package com.quanshu.exchange.ui.gui.message.chat;

import android.Manifest;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baselibrary.bigimage.ImageLoadActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVideoMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.PathUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.chat.ChatCommonUtils;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.config.PermissionObserver;
import com.quanshu.exchange.support.db.GroupDao;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.RPStatusEntity;
import com.quanshu.exchange.support.entity.RobResultEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpStringData;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.message.chat.expand.VideoCallActivity;
import com.quanshu.exchange.ui.gui.message.chat.expand.VoiceCallActivity;
import com.quanshu.exchange.ui.gui.message.chat.redpackage.DialogRedPackageExpired;
import com.quanshu.exchange.ui.gui.message.chat.redpackage.DialogRobRedPackage;
import com.quanshu.exchange.ui.gui.message.chat.redpackage.RecordResultActivity;
import com.quanshu.exchange.ui.gui.message.chat.redpackage.RedPackageTypeActivity;
import com.quanshu.exchange.ui.gui.message.chat.redpackage.SingleRedPackageActivity;
import com.quanshu.exchange.ui.gui.message.chat.row.OnChatItemClickListener;
import com.quanshu.exchange.ui.gui.message.chat.row.ShowVideoActivity;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VoiceReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VoiceSendViewHolder;
import com.quanshu.exchange.ui.gui.message.friends.PrivateChatDetailActivity;
import com.quanshu.exchange.ui.gui.message.friends.UserDetailActivity;
import com.quanshu.exchange.ui.gui.message.group.GroupChatDetailActivity;
import com.quanshu.exchange.ui.gui.message.group.UpdateGroupActivity;
import com.quanshu.exchange.ui.gui.message.group.dialog.DialogGroupMenu;
import com.quanshu.exchange.ui.widget.popwindow.PopTipItem;
import com.quanshu.exchange.ui.widget.popwindow.PopTipView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.quanshu.exchange.support.chat.ChatConstant.Chat_ext_attr_photo;

/**
 * Created by jye on 2017/12/7.
 */

public class ChatActivity extends RxAppCompatActivity {

    public UserEntity currentUser;

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.chat_title)
    TextView chatTitle;
    @BindView(R.id.chat_right_btn)
    LinearLayout chatRightBtn;
    @BindView(R.id.head_view)
    RelativeLayout headView;
    @BindView(R.id.chat_message_list)
    ChatMessageList chatMessageList;
    @BindView(R.id.chat_bottom)
    ChatBottomView chatBottom;
    @BindView(R.id.chat_right_btn_image)
    ImageView chatRightBtnImage;
    private UserEntity userEntity;
    private int chatType;
    private String destId;
    private EMConversation conversation;
    private boolean isMessageListInited;
    private GroupEntity groupEntity;
    private MyMessageListener messageListener;
    private String toReplyId;

    public static final int RED_PACKAGE = 10; // 创建红包

    private DialogRobRedPackage robRedPackageDialog;
    private DialogRedPackageExpired redPackageExpiredDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_view);
        currentUser = MyApplication.getInstance().getCurrentUser();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ButterKnife.bind(this);
        initIntent();
        requestPermissions();
        initListener();
    }

    private void initIntent() {
        chatType = getIntent().getIntExtra("CHAT_TYPE", 1);
        destId = getIntent().getStringExtra("conversationID");
    }

    private void initView() {
        chatBottom.init(getSupportFragmentManager(), chatType);
        if (chatType == ChatConstant.CHAT_TYPE_SINGLE) {
            conversation = EMClient.getInstance().chatManager().getConversation(destId,
                    AppUtils.getConversationType(chatType), true);
            chatRightBtnImage.setBackgroundResource(R.drawable.massage_one);
            userEntity = UserDao.getInstance().query(destId);
            if (userEntity == null) {
                doSyncFriend();
                chatTitle.setText("聊天");
            } else {
                initPrivateChat();
            }
        } else if (chatType == ChatConstant.CHAT_TYPE_GROUP) {
            conversation = EMClient.getInstance().chatManager().getConversation(destId,
                    AppUtils.getConversationType(chatType), true);
            chatRightBtnImage.setBackgroundResource(R.drawable.icon_group_more);
            groupEntity = GroupDao.getInstance().query(destId);
            if (groupEntity == null) {
                doSyncGroup();
                chatTitle.setText("聊天");
            } else {
                initGroupChat();
            }
        }
        doInitConversation();
        isMessageListInited = true;
        if (conversation != null) {
            conversation.markAllMessagesAsRead();
        }
        messageListener = new MyMessageListener();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    private void initGroupChat() {
        chatTitle.setText(groupEntity.getGroup_name());
        chatMessageList.setConversation(conversation, groupEntity.getOwner());
        // 设置背景
        chatMessageList.setChatBackground(groupEntity.getVisible());
    }

    private void initPrivateChat() {
        chatTitle.setText(AppUtils.getUserName(userEntity));
        chatMessageList.setConversation(conversation, null);
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(chatRightBtn, aVoid -> goChatSetting());
        chatBottom.getSendClick().subscribe(s -> doSendTextMessage(s, null));
        chatBottom.chatExpandView.getClick().subscribe(s -> doClickExpandMenuImage(s));
        chatBottom.chatRecorderView.setVoiceRecordCallback((voiceFilePath, voiceTimeLength) -> {
            if (voiceTimeLength < 1) {
                ToastHelper.toast("音频太短，不能发送");
                return;
            }
            sendVoiceMessage(voiceFilePath, voiceTimeLength, null);
        });
    }

    private void doInitConversation() {
        if (conversation != null) {
            final List<EMMessage> msgs = conversation.getAllMessages();
            int msgCount = msgs != null ? msgs.size() : 0;
            if (msgCount < conversation.getAllMsgCount() && msgCount < Config.Chat_MSG_PAGE) {
                String msgId = null;
                if (msgs != null && msgs.size() > 0) {
                    msgId = msgs.get(0).getMsgId();
                }
                conversation.loadMoreMsgFromDB(msgId, Config.Chat_MSG_PAGE - msgCount);
            }
            if (chatMessageList != null && chatMessageList.getAdapter() != null) {
                chatMessageList.getAdapter().setOnChatItemClickListener(new OnChatItemClickListener() {
                    @Override
                    public void onReplyClick(String toReplyId) {
                        doClickReply(toReplyId);
                    }

                    @Override
                    public void onBubbleClick(EMMessage emMessage, RecyclerView.ViewHolder viewHolder) {
                        doClickBubble(emMessage, viewHolder);
                    }

                    @Override
                    public void onBubbleLongClick(EMMessage emMessage, View view, ViewGroup viewGroup) {
                        doLongClickBubble(emMessage, view, viewGroup);
                    }

                    @Override
                    public void onAvatarClick(EMMessage emMessage) {
                        doClickAvatar(emMessage);
                    }
                });
            }
        }
    }

    private void doClickAvatar(EMMessage emMessage) {
        if (chatType == ChatConstant.CHAT_TYPE_GROUP && !groupEntity.getOwner().equals(currentUser.getMemberid())) {
            return;
        }
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getUser(AppUtils.getSignParams(emMessage.getFrom()), emMessage.getFrom())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<UserEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserEntity> response) {
                        UserEntity tmp = response.getInfo();
                        if (tmp != null) {
                            Intent intent = new Intent(ChatActivity.this, UserDetailActivity.class);
                            intent.putExtra("UserEntity", tmp);
                            startActivity(intent);
                        }
                    }
                });
    }

    private void doLongClickBubble(EMMessage emMessage, View view, ViewGroup viewGroup) {
        int type = ChatCommonUtils.getChatMessageType(emMessage);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        float OldListY = (float) location[1];
        float OldListX = (float) location[0];

        List<PopTipItem> popTipItems = new ArrayList<>();
        PopTipItem popTipItem;

        // 文字
        if (type == ChatConstant.MESSAGE_TYPE_TXT) {
            popTipItem = new PopTipItem("复制");
            popTipItems.add(popTipItem);
        }
        int is_toAll = groupEntity.getVisible();
        // 如果是群消息，群不是公开的且当前用户是群主
        if (chatType == ChatConstant.CHAT_TYPE_GROUP && is_toAll != 1 &&
                emMessage.direct() == EMMessage.Direct.RECEIVE &&
                currentUser.getMemberid().equals(groupEntity.getOwner())) {
            popTipItem = new PopTipItem("设为公开");
            popTipItems.add(popTipItem);
        }
        if (popTipItems.size() < 1) {
            return;
        }

        new PopTipView.Builder(ChatActivity.this, viewGroup, (int) OldListX + view.getWidth() / 2, (int) OldListY)
                .addItems(popTipItems)
                .setOnItemClickListener(new PopTipView.OnItemClickListener() {
                    @Override
                    public void onItemClick(String str, final int position) {
                        PopTipItem item = popTipItems.get(position);
                        if (item.getTitle().equals("复制")) {
                            EMTextMessageBody txtBody = (EMTextMessageBody) emMessage.getBody();
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                            // 将文本内容放到系统剪贴板里。
                            cm.setText(txtBody.getMessage());

                        } else if (item.getTitle().equals("设为公开")) {
                            // 获取消息实体
                            EMMessageBody messageBody = emMessage.getBody();
                            // 文字消息
                            if (messageBody instanceof EMTextMessageBody) {
                                String text = ((EMTextMessageBody) messageBody).getMessage();
                                doSendTextMessage(text, emMessage.getFrom());
                            } else {
                                openAttachMessage(emMessage);
                            }
                        }
                    }

                    @Override
                    public void dismiss() {

                    }
                })
                .create();
    }


    private void openAttachMessage(EMMessage emMessage) {
        EMMessageBody messageBody = emMessage.getBody();
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    int type = ChatCommonUtils.getChatMessageType(emMessage);
                    // 图片
                    if (type == ChatConstant.MESSAGE_TYPE_IMAGE) {
                        String localUrl = ((EMImageMessageBody) messageBody).getLocalUrl();
                        File temp = new File(localUrl);
                        final String tempPath = temp.getParent() + "/temp_" + temp.getName();
                        new File(tempPath).renameTo(new File(localUrl));
                        sendImageMessage(localUrl, emMessage.getFrom());
                    }
                    // 视频
                    else if (type == ChatConstant.MESSAGE_TYPE_VIDEO) {
                        String localUrl = ((EMVideoMessageBody) messageBody).getLocalUrl();
                        File temp = new File(localUrl);
                        final String tempPath = temp.getParent() + "/temp_" + temp.getName();
                        new File(tempPath).renameTo(new File(localUrl));

                        String thumbPath = ((EMVideoMessageBody) messageBody).getLocalThumb();
                        File tempThumb = new File(thumbPath);
                        final String tempThumbPath = tempThumb.getParent() + "/temp_" + tempThumb.getName();
                        new File(tempThumbPath).renameTo(new File(thumbPath));
                        int length = (int) ((EMVideoMessageBody) messageBody).getVideoFileLength();
                        sendVideoMessage(localUrl, thumbPath, length, emMessage.getFrom());
                    }
                    // 音频
                    else if (type == ChatConstant.MESSAGE_TYPE_VOICE) {
                        String localUrl = ((EMVoiceMessageBody) messageBody).getLocalUrl();
                        File temp = new File(localUrl);
                        final String tempPath = temp.getParent() + "/temp_" + temp.getName();
                        new File(tempPath).renameTo(new File(localUrl));
                        int length = ((EMVoiceMessageBody) messageBody).getLength();
                        sendVoiceMessage(localUrl, length, emMessage.getFrom());
                    }
                });
            }

            @Override
            public void onError(int code, String error) {
            }

            @Override
            public void onProgress(int progress, String status) {
            }
        });
        EMClient.getInstance().chatManager().downloadAttachment(emMessage);
    }

    private void doClickBubble(EMMessage emMessage, RecyclerView.ViewHolder viewHolder) {
        if (emMessage != null) {
            int type = ChatCommonUtils.getChatMessageType(emMessage);
            // 文字
            if (type == ChatConstant.MESSAGE_TYPE_TXT) {
            }
            // 图片
            else if (type == ChatConstant.MESSAGE_TYPE_IMAGE) {
                doClickImage(emMessage);
            }
            // 视频
            else if (type == ChatConstant.MESSAGE_TYPE_VIDEO) {
                doClickVideo(emMessage);
            }
            // 视频通话
            else if (type == ChatConstant.MESSAGE_TYPE_VIDEO_CALL) {
            }
            // 音频
            else if (type == ChatConstant.MESSAGE_TYPE_VOICE) {
                if (viewHolder instanceof VoiceSendViewHolder) {
                    ((VoiceSendViewHolder) viewHolder).play(emMessage);
                } else if (viewHolder instanceof VoiceReceiveViewHolder) {
                    ((VoiceReceiveViewHolder) viewHolder).play(emMessage);
                }
            }
            // 音频通话
            else if (type == ChatConstant.MESSAGE_TYPE_VOICE_CALL) {
            }
            // 红包
            else if (type == ChatConstant.MESSAGE_TYPE_RED_PACKAGE) {
                doClickRP(emMessage);
            }
        }
    }

    private void doClickVideo(EMMessage emMessage) {
        EMVideoMessageBody videoBody = (EMVideoMessageBody) emMessage.getBody();
        if (EMClient.getInstance().getOptions().getAutodownloadThumbnail()) {
        } else {
            if (videoBody.thumbnailDownloadStatus() == EMFileMessageBody.EMDownloadStatus.DOWNLOADING ||
                    videoBody.thumbnailDownloadStatus() == EMFileMessageBody.EMDownloadStatus.PENDING ||
                    videoBody.thumbnailDownloadStatus() == EMFileMessageBody.EMDownloadStatus.FAILED) {
                // retry download with click event of user
                EMClient.getInstance().chatManager().downloadThumbnail(emMessage);
                return;
            }
        }
        Intent intent = new Intent(this, ShowVideoActivity.class);
        intent.putExtra("msg", emMessage);
        if (emMessage != null && emMessage.direct() == EMMessage.Direct.RECEIVE && !emMessage.isAcked()
                && emMessage.getChatType() == EMMessage.ChatType.Chat) {
            try {
                EMClient.getInstance().chatManager().ackMessageRead(emMessage.getFrom(), emMessage.getMsgId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        startActivity(intent);

    }

    private void doClickImage(EMMessage emMessage) {
        EMImageMessageBody imgBody = (EMImageMessageBody) emMessage.getBody();

        ArrayList<String> urlList = new ArrayList<>();
        if (emMessage.direct() == EMMessage.Direct.SEND) {
            String localFile = imgBody.getLocalUrl();
            urlList.add(localFile);
        } else {
            String remoteFile = imgBody.getRemoteUrl();
            urlList.add(remoteFile);
        }

        Intent intent = new Intent(this, ImageLoadActivity.class);
        intent.putStringArrayListExtra("urlList", urlList);
        intent.putExtra("image_position", 0);
        startActivity(intent);
    }

    private void doClickRP(EMMessage emMessage) {

        try {
            String redPackageId = emMessage.getStringAttribute(ChatConstant.Chat_ext_attr_red_package_id);
            String redPackageName = emMessage.getStringAttribute(ChatConstant.Chat_ext_attr_red_package_name);
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .getRedPackageStatus(AppUtils.getSignParams(
                            redPackageId, emMessage.getFrom(), currentUser.getMemberid()),
                            redPackageId, emMessage.getFrom(), currentUser.getMemberid())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<RPStatusEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<RPStatusEntity> response) {
                            RPStatusEntity statusEntity = response.getInfo();
                            //1 :手慢了 2：已经领了 3：可以领 4：过期红包
                            if (statusEntity.getStatus() == 3) {
                                robRedPackageDialog = new DialogRobRedPackage(ChatActivity.this);
                                robRedPackageDialog.show();
                                String avatar = "";
                                try {
                                    avatar = emMessage.getStringAttribute(Chat_ext_attr_photo);
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                }
                                robRedPackageDialog.setViewInfo(redPackageName, avatar, emMessage.getFrom());
                                robRedPackageDialog.getRobSubject().subscribe(aVoid -> {
                                            robRedPackageDialog.dismiss();
                                            doRob(redPackageId, emMessage.getFrom(), emMessage);
                                        }
                                );

                            } else if (statusEntity.getStatus() == 1 || statusEntity.getStatus() == 4) {
                                redPackageExpiredDialog = new DialogRedPackageExpired(ChatActivity.this);
                                redPackageExpiredDialog.show();
                                String avatar = "";
                                try {
                                    avatar = emMessage.getStringAttribute(Chat_ext_attr_photo);
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                }
                                redPackageExpiredDialog.setViewInfo(redPackageName, avatar, emMessage.getFrom(), 1);
                                redPackageExpiredDialog.getCheckDetailSubject().subscribe(aVoid -> {
                                    goRecordActivity(redPackageId, emMessage.getFrom(), statusEntity.getStatus());
                                    redPackageExpiredDialog.dismiss();
                                });
                            } else if (statusEntity.getStatus() == 2) {
                                goRecordActivity(redPackageId, emMessage.getFrom(), statusEntity.getStatus());
                            }
                        }
                    });
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    private void goRecordActivity(String redPackageId, String redPackageFrom, int status) {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .robRedPackage("", redPackageId, redPackageFrom, currentUser.getMemberid(), status)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<RobResultEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<RobResultEntity> response) {
                        Intent intent = new Intent(ChatActivity.this, RecordResultActivity.class);
                        if (response.getInfo().getRed_info() != null) {
                            intent.putExtra("RPInfoBean", response.getInfo().getRed_info());
                        }
                        if (response.getInfo().getReceive_info() != null) {
                            intent.putExtra("List<RobMemberBean>", (Serializable) response.getInfo().getReceive_info());
                        }
                        if (response.getInfo().getMy_receive() != null) {
                            intent.putExtra("MyRobBean", response.getInfo().getMy_receive());
                        }
                        startActivity(intent);
                    }
                });
    }

    private void doRob(String redPackageId, String redPackageFrom, EMMessage emMessage) {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .robRedPackage("", redPackageId, redPackageFrom, currentUser.getMemberid(), 3)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<RobResultEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<RobResultEntity> response) {
                        Intent intent = new Intent(ChatActivity.this, RecordResultActivity.class);
                        if (response.getInfo().getRed_info() != null) {
                            intent.putExtra("RPInfoBean", response.getInfo().getRed_info());
                        }
                        if (response.getInfo().getReceive_info() != null) {
                            intent.putExtra("List<RobMemberBean>", (Serializable) response.getInfo().getReceive_info());
                        }
                        if (response.getInfo().getMy_receive() != null) {
                            intent.putExtra("MyRobBean", response.getInfo().getMy_receive());
                            emMessage.setAttribute(ChatConstant.Chat_ext_attr_red_package_is_robed, true);
                            conversation.updateMessage(emMessage);
                        }
                        startActivity(intent);
                    }
                });
    }

    private void goChatSetting() {
        if (chatType == ChatConstant.CHAT_TYPE_SINGLE) {
            Intent intent = new Intent(ChatActivity.this, PrivateChatDetailActivity.class);
            intent.putExtra("UserEntity", userEntity);
            startActivity(intent);
        } else if (chatType == ChatConstant.CHAT_TYPE_GROUP) {
            DialogGroupMenu groupMenu = new DialogGroupMenu(this);
            groupMenu.show();
            // 如果是群主
            if (groupEntity.getOwner().equals(currentUser.getMemberid())) {
                groupMenu.setIsOwner(true);
            } else {
                groupMenu.setIsOwner(false);
            }
            groupMenu.getSendDocSubject().subscribe();
            groupMenu.getCheckDocSubject().subscribe();
            groupMenu.getCheckDetailSubject().subscribe(o -> {
                groupMenu.dismiss();
                goDetailActivity();
            });

            groupMenu.getUpdDetailSubject().subscribe(o -> {
                groupMenu.dismiss();
                goUpdateActivity();
            });
        }
    }

    private void doSendTextMessage(String str, String src) {
        if (TextUtils.isEmpty(str)) {
            ToastHelper.toast("不能发送空消息");
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(str, destId);
        sendMsg(message, src);
    }

    protected void sendImageMessage(String imagePath, String src) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, true, destId);
        sendMsg(message, src);
    }

    protected void sendVoiceMessage(String filePath, int length, String src) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, destId);
        sendMsg(message, src);
    }

    protected void sendVideoMessage(String videoPath, String thumbPath, int videoLength, String
            src) {
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, thumbPath, videoLength, destId);
        sendMsg(message, src);
    }

    protected void sendRedPackageMessage(String redPackageId, String redPackageName) {
        EMMessage message = EMMessage.createTxtSendMessage("积分红包", destId);
        message.setAttribute(ChatConstant.Chat_ext_attr_red_package_id, redPackageId);
        message.setAttribute(ChatConstant.Chat_ext_attr_red_package_name, redPackageName);
        sendMsg(message, null);
    }

    private void sendMsg(EMMessage message, String orginalSrc) {
        List<String> hasBeenDelFriend = MyApplication.getInstance().getHasBeenDelFriend();
        if (hasBeenDelFriend != null && hasBeenDelFriend.contains(destId)) {
            ToastHelper.toast("请先添加为好友");
            return;
        }
        if (chatType == ChatConstant.CHAT_TYPE_SINGLE) {
            message.setChatType(EMMessage.ChatType.Chat);
        } else if (chatType == ChatConstant.CHAT_TYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
            message.setAttribute(ChatConstant.Chat_group_id, groupEntity.getGroup_id());
            message.setAttribute(ChatConstant.Chat_group_photo, groupEntity.getGroup_photo());
            message.setAttribute(ChatConstant.Chat_group_name, groupEntity.getGroup_name());
            message.setAttribute(ChatConstant.Chat_group_owner, groupEntity.getOwner());
            if (toReplyId != null && toReplyId.trim().length() > 0) {
                message.setAttribute(ChatConstant.Chat_reply_member, toReplyId);
            }
            // 是不是公开群
            if (groupEntity.getVisible() == 1) {
                message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, true);
            } else {
                message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, false);
            }
        }
        if (orginalSrc != null) {
            message.setDirection(EMMessage.Direct.SEND);
            message.setFrom(currentUser.getMemberid());
            message.setAttribute(ChatConstant.Chat_orginal_src, orginalSrc);
        }
        message.setAttribute(ChatConstant.Chat_send_member_id, currentUser.getMemberid());
        message.setAttribute(Chat_ext_attr_photo, currentUser.getAvatar());
        message.setAttribute(ChatConstant.Chat_ext_attr_nickname, currentUser.getNickname());
        EMClient.getInstance().chatManager().saveMessage(message);
        chatMessageList.refreshSelectLast();
        toReplyId = null;
        chatBottom.chatInputView.getInputText().setHint("");
    }

    private void doClickReply(String toReplyId) {
        this.toReplyId = toReplyId;
        EditText editText = chatBottom.chatInputView.getInputText();
        editText.setFocusable(true);
        editText.requestFocus();
        toggleSoftInput();
        String str = toReplyId;
        UserEntity userEntity = UserDao.getInstance().query(toReplyId);
        if (userEntity != null) {
            str = AppUtils.getUserName(userEntity);
        }
        editText.setHint("回复: " + str);
    }

    private void doClickExpandMenuImage(String s) {
        if (s.equals("相册")) {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .forResult(PictureConfig.CHOOSE_REQUEST);

        } else if (s.equals("拍照")) {
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .forResult(PictureConfig.CHOOSE_REQUEST);

        } else if (s.equals("小视频")) {
            Intent intent = new Intent(this, VideoRecordActivity.class);
            startActivityForResult(intent, 100);
        } else if (s.equals("视频聊天")) {
            if (!EMClient.getInstance().isConnected())
                Toast.makeText(this, R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
            else {
                Intent intent = new Intent(this, VideoCallActivity.class);
                intent.putExtra("username", destId);
                intent.putExtra("isComingCall", false);
                startActivity(intent);
            }
        } else if (s.equals("语音聊天")) {
            if (!EMClient.getInstance().isConnected())
                Toast.makeText(this, R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
            else {
                Intent intent = new Intent(this, VoiceCallActivity.class);
                intent.putExtra("username", destId);
                intent.putExtra("isComingCall", false);
                startActivity(intent);
            }
        } else if (s.equals("红包")) {

            // 如果是群聊
            if (chatType == ChatConstant.CHAT_TYPE_GROUP) {
                if (groupEntity != null) {
                    NetClient.getInstance()
                            .getNetService(UserInterface.class)
                            .getGroupMembersCount(AppUtils.getSignParams(groupEntity.getHx_groupid()), groupEntity.getHx_groupid())
                            .compose(new BaseTransformer<>(this))
                            .subscribe(new BaseObserver<BaseResponse<TmpStringData>>() {
                                @Override
                                public void onSuccess(BaseResponse<TmpStringData> response) {
                                    Intent intent = new Intent(ChatActivity.this, RedPackageTypeActivity.class);
                                    intent.putExtra("sumMembers", response.getInfo().getCount());
                                    intent.putExtra("destId", destId);
                                    startActivityForResult(intent, RED_PACKAGE);
                                }
                            });
                }
            }
            // 如果是单聊
            else if (chatType == ChatConstant.CHAT_TYPE_SINGLE) {
                Intent intent = new Intent(ChatActivity.this, SingleRedPackageActivity.class);
                intent.putExtra("destId", destId);
                startActivityForResult(intent, RED_PACKAGE);
            }
        }
    }

    class MyMessageListener implements EMMessageListener {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            if (messages != null && messages.size() > 0) {
                for (EMMessage message : messages) {
                    String username = null;
                    // group message
                    if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                        username = message.getTo();
                    } else {
                        // single chat message
                        username = message.getFrom();
                    }
                    // if the message is for current conversation
                    if (username.equals(destId) || message.getTo().equals(destId)) {
                        runOnUiThread(() -> {
                            chatMessageList.refreshSelectLast();
                            if (conversation != null) {
                                conversation.markMessageAsRead(message.getMsgId());
                            }
                        });
                    }
                }
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            if (messages != null) {
                for (EMMessage emMessage : messages) {
                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) emMessage.getBody();
                    if (cmdMsgBody != null) {
                        String action = cmdMsgBody.action();//获取自定义action
//                        if (action != null && action.equals(ChatConstant.Chat_ext_attr_is_toAll)) {
//                            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(emMessage.getTo(),
//                                    AppUtils.getConversationType(ChatConstant.CHAT_TYPE_GROUP), false);
//                            if (conversation != null) {
//                                try {
//                                    String messageId = emMessage.getStringAttribute("message_id");
//                                    if (messageId != null) {
//                                        EMMessage message = conversation.getMessage(messageId, false);
//                                        message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, true);
//                                        conversation.updateMessage(emMessage);
//                                        chatMessageList.getAdapter().refreshToLast();
//                                    }
//                                } catch (HyphenateException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        } else
                        if (action != null && action.equals("group_visible")) {
                            boolean visible = emMessage.getBooleanAttribute("visible", false);
                            runOnUiThread(() -> {
                                if (groupEntity != null) {
                                    if (visible) {
                                        chatMessageList.setChatBackground(1);
                                    } else {
                                        chatMessageList.setChatBackground(0);
                                    }
                                }
                            });
                            if (groupEntity != null) {
                                if (visible) {
                                    groupEntity.setVisible(1);
                                } else {
                                    groupEntity.setVisible(0);
                                }
                                GroupDao.getInstance().save(groupEntity);
                            }
                        } else if (action != null && action.equals("group_change_owner")) {
                            try {
                                String newOwner = emMessage.getStringAttribute("new_owner");
                                groupEntity.setOwner(newOwner);
                                GroupDao.getInstance().save(groupEntity);

                            } catch (HyphenateException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            if (isMessageListInited) {
                chatMessageList.refresh();
            }
        }

        @Override
        public void onMessageDelivered(List<EMMessage> messages) {
            if (isMessageListInited) {
                chatMessageList.refresh();
            }
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {

        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            if (isMessageListInited) {
                chatMessageList.refresh();
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (AppUtils.inRangeOfView(chatMessageList, event)) {
            chatBottom.chatInputView.hideKeyboard();
            chatBottom.hideBottomContainer();
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {

                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                String path = selectList.get(0).getPath();
                sendImageMessage(path, null);

            } else if (requestCode == 100) {
                Uri uri = data.getParcelableExtra("uri");
                String[] projects = new String[]{MediaStore.Video.Media.DATA,
                        MediaStore.Video.Media.DURATION};
                Cursor cursor = getContentResolver().query(
                        uri, projects, null,
                        null, null);
                int duration = 0;
                String filePath = null;

                if (cursor.moveToFirst()) {
                    // path：MediaStore.Audio.Media.DATA
                    filePath = cursor.getString(cursor
                            .getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                    // duration：MediaStore.Audio.Media.DURATION
                    duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                }
                if (cursor != null) {
                    cursor.close();
                    cursor = null;
                }
                File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(filePath, 3);
                    ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.close();
                    sendVideoMessage(filePath, file.getAbsolutePath(), duration, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (requestCode == RED_PACKAGE) {

                String redPackageId = data.getStringExtra("redPackageId");
                String redPackageName = data.getStringExtra("redPackageName");
                sendRedPackageMessage(redPackageId, redPackageName);

            } else {
                if (data.getBooleanExtra("exit", false)) {
                    finish();
                }
            }
        }
    }

    private void goDetailActivity() {
        Intent intent = new Intent(this, GroupChatDetailActivity.class);
        groupEntity.setIs_have(1);
        intent.putExtra("GroupEntity", groupEntity);
        startActivityForResult(intent, 30);
    }

    private void goUpdateActivity() {
        Intent intent = new Intent(this, UpdateGroupActivity.class);
        intent.putExtra("GroupEntity", groupEntity);
        startActivity(intent);
    }

    private void doSyncGroup() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getGroupInfo(AppUtils.getSignParams(currentUser.getMemberid(), destId), currentUser.getMemberid(), destId)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<GroupEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<GroupEntity> response) {
                        groupEntity = response.getInfo();
                        GroupDao.getInstance().save(groupEntity);
                        initGroupChat();
                    }
                });
    }

    private void doSyncFriend() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getUser(AppUtils.getSignParams(destId), destId)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<UserEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserEntity> response) {
                        userEntity = response.getInfo();
                        UserDao.getInstance().save(userEntity);
                        initPrivateChat();
                    }
                });
    }

    public void toggleSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void requestPermissions() {
        new RxPermissions(this)
                .request(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)
                .subscribe(new PermissionObserver(this) {
                    @Override
                    public void onSuccess() {
                        goToNext();
                    }
                });
    }

    private void goToNext() {
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.getInstance().setCurrentChatUsername(destId);
        if (chatMessageList != null) {
            chatMessageList.refreshSelectLast();
        }
        if (groupEntity != null) {
            groupEntity = GroupDao.getInstance().query(destId);
            if (chatMessageList != null) {
                chatMessageList.setChatBackground(groupEntity.getVisible());
            }
        }
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        MyApplication.getInstance().setCurrentChatUsername("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }


}
